﻿using System.Runtime.InteropServices;
using Daemon.Common.Const;
using Daemon.Common.Exceptions;
using Daemon.Service.Contract;
using Daemon.Model;
using Microsoft.AspNetCore.Http;
using System.Linq;
using System;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Mvc;
using Daemon.Repository.Contract;
namespace Daemon.Service
{
    public class AdminUserService : IAdminUserService
    {
        private readonly IAdminUserRepository _adminUserRepository;
        private readonly IAdminRoleRepository _adminRoleRepository;
        private readonly IUserRoleRepository _userRoleRepository;
        public AdminUserService(IAdminUserRepository adminUserRepository,
        IAdminRoleRepository adminRoleRepository,
        IUserRoleRepository userRoleRepository)
        {
            _adminUserRepository = adminUserRepository;
            _adminRoleRepository = adminRoleRepository;
            _userRoleRepository = userRoleRepository;
        }

        public AdminUser Register(AdminUser user)
        {
            var phoneRegex = new Regex(RegexConst.PhoneRegexExpression);
            if (!phoneRegex.IsMatch(user.Phone))
            {
                throw new BusinessException((int)BusinessCode.InCorrect, MessageConst.PhoneError);
            }

            var existUser = false;
            existUser = _adminUserRepository.FindAll().Any(r => r.Phone == user.Phone);
            if (existUser)
            {
                throw new BusinessException((int)BusinessCode.Exist, MessageConst.PhoneExistError);
            }

            var adminUser = _adminUserRepository.AddByDBContext(user);
            var teacherRole = _adminRoleRepository.FindAll().First(r => r.Name == "老师");
            var userRole = new UserRole() { UserId = adminUser.Id, RoleId = teacherRole.Id };
            _userRoleRepository.AddByDBContext(userRole);
            return adminUser;
        }
    }
}
